package com.zhenwei.zscm.config.interceptors;

import com.zhenwei.zscm.common.exception.CustomException;
import com.zhenwei.zscm.common.exception.UnauthorizedException;
import com.zhenwei.zscm.common.utils.JwtHandler;
import com.zhenwei.zscm.common.base.RestMsg;
import com.zhenwei.zscm.common.base.UserContext;
import com.zhenwei.zscm.model.dto.user.UserDTO;
import com.zhenwei.zscm.repo.UserRepo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class RequestInterceptor implements HandlerInterceptor {

    @Autowired
    private UserRepo userRepo;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestUri = request.getRequestURI();
        System.out.println("Request URI: " + requestUri);

        // 检查请求头中的access-token
        String accessTokenFromHeader = request.getHeader("access-token");
        String accessToken = accessTokenFromHeader != null ? accessTokenFromHeader : request.getParameter("at");

        if (accessToken == null || accessToken.isEmpty()) {
            // 返回未授权的错误码
            throw new UnauthorizedException(RestMsg.UNAUTHORIZED);
        }
        // 验证token有效性
        String userId = JwtHandler.validJwt(accessToken);
        if (userId.isEmpty()) {

            throw new UnauthorizedException(RestMsg.TOKEN_EXPIRED);
        }
        // token有效，放行请求
        UserDTO user = userRepo.getUserById(userId);
        if(user == null) {
            // 返回token无效的错误信息
            throw new CustomException(RestMsg.TOKEN_EXPIRED);
        }
        UserContext.setCurrentUser(user);
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求完成后清除上下文
        UserContext.clear();
    }
}
